package com.ibm.db2oncampus.portal.domain.persistence.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;

import com.ibm.db2oncampus.portal.domain.domain.Domain;
import com.ibm.db2oncampus.portal.domain.persistence.DomainDao;
import com.ibm.db2oncampus.portal.framework.orm.hibernate.support.HibernateDaoSupport;

/**
 * 
 * @author Wellington
 *
 */
public class DomainDaoImpl extends HibernateDaoSupport<Domain> implements DomainDao {

    public DomainDaoImpl() {
    }

	@Override
	public List<String> listDomainTypeByType(String type) {
		Criteria domainCriteria = getSession().createCriteria(Domain.class);
		domainCriteria.add(Expression.ilike("id.type", type, MatchMode.ANYWHERE));
		domainCriteria.setProjection(Projections.distinct(Projections.property("id.type")));
		domainCriteria.addOrder(Order.asc("id.type"));
		return domainCriteria.list();
	}

	@Override
	public List<Domain> listDomainValueByType(String type) {
		Criteria domainCriteria = getSession().createCriteria(Domain.class);
		domainCriteria.add(Expression.eq("id.type", type));
		domainCriteria.addOrder(Order.asc("id.type"));
		return domainCriteria.list();
	}

	@Override
	public Domain findDomainValueByTypeAndValue(String type, String value) {
		Criteria domainCriteria = getSession().createCriteria(Domain.class);
		domainCriteria.add(Expression.eq("id.type", type));
		domainCriteria.add(Expression.eq("id.value", value));
		List<Domain> list = domainCriteria.list();
		if (list != null && (! list.isEmpty())) {
			return list.get(0);
		} else {
			return null;
		}
	}

	@Override
	public void saveDomain(Domain domain) {
		
		Domain searchDomain = this.findDomainValueByTypeAndValue(domain.getId().getType(), domain.getId().getValue());
		
		getSession().setFlushMode(FlushMode.AUTO);
		if (searchDomain == null) {
			getSession().save(domain);
		} else {
			searchDomain.setDescription(domain.getDescription());
			getSession().update(searchDomain);
		}
    	
    	getHibernateTemplate().flush();		
		
	}

	@Override
	public List<Domain> listDomainNotInCollectionByType(String type, List<Domain> domain) {
		
		String[] values = new String[domain.size()];
		for (int i = 0; i < domain.size(); i++) {
			values[i] = domain.get(i).getId().getValue().toUpperCase();
		}
		
		Criteria criteriaDomain = getSession().createCriteria(Domain.class);
		criteriaDomain.add(Expression.eq("id.type", type));
		criteriaDomain.add(Expression.not(Expression.in("id.value", values)));
		return criteriaDomain.list();
	}
}
